package com.dandan.mobilelover.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dandan.mobilelover.entity.User;

public class LoginFilter implements Filter {
//	private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	public void destroy() {
	}

	public void init(FilterConfig config) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) 
			throws IOException, ServletException {
		HttpServletRequest servletReuqest = (HttpServletRequest)request;
		HttpServletResponse serlvetResponse = (HttpServletResponse)response;
		User user = (User) servletReuqest.getSession().getAttribute("currentUser");
		String uri = servletReuqest.getRequestURI();
		//logger.info("request uri:"+uri);
		
		
		String[] noFilterPattern = {"/css/","/js/","/images/","/tmp/","/upload/","/uploads/","/photo/","/attachment/"};
		boolean doFilter = true;
		for (String string : noFilterPattern) {
			if(uri.indexOf(string)!=-1){
				doFilter = false;
				break;
			}
		}
		if(uri.endsWith("/mobile_lover_webservice")||uri.endsWith("/login") || uri.endsWith("/")){
			doFilter = false;
		}
		if(doFilter){
			if(user==null){
				serlvetResponse.sendRedirect(servletReuqest.getContextPath());
			}else{
				chain.doFilter(servletReuqest, serlvetResponse);
			}
		}else{
			chain.doFilter(servletReuqest, serlvetResponse);
		}
	}
}
